package com.jketing.controller.ams.work;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jketing.controller.BaseController;
import com.jketing.entity.ams.work.MaizeExperiment;
import com.jketing.entity.ams.work.Variety;
import com.jketing.poi.word.MaizeExperimentWordBuilder;
import com.jketing.service.ams.sys.OperationService;
import com.jketing.service.ams.work.MaizeExperimentService;
import com.jketing.spring.mvc.office.view.MaizeBillExcelView;
import com.jketing.utils.ImageUtil;

/**
 * Controller 请求处理
 * 
 * @author  李荣华
 * @version v1.0
 * @date    2018-10-15
 * @since   Spring-mvc 4.3.8
 */
@Controller
@RequestMapping("/maizeExperiment")
public class MaizeExperimentController extends BaseController<MaizeExperiment,String>{
	/**
	 *  service 	服务层自动注入
	 */
	private MaizeExperimentService service;
	/**
	 *  service 自动注入服务层操作实例
	 */
	@Autowired
	public void setService(MaizeExperimentService service) {
		super.setBaseService(service);
		this.service = service;
	}
	/**
	 *  bs 	服务层自动注入
	 */
	@Autowired
	private OperationService bs;
	
	@Override
	protected String getPrefixPath() {
		return "work/MaizeExperiment/";
	}

	@Override
	protected String getQueryMode() {
		return "Entity";
	}
	
	@Override
	protected MaizeExperiment getQuery(MaizeExperiment query) {
		String type = (String)getSession().getAttribute("MaizeExperiment_type");
		if("redirect".equals(type)) {
			if("Entity".equals(getQueryMode())) {
				query = (MaizeExperiment)getSession().getAttribute("MaizeExperiment_query");
			}
		}
		//可在此处增加修改查询条件的代码
		//if(query.getAltitude().floatValue()==0) query.setAltitude(null);//默认前台不写条件为设为0，0不能生成查询条件
		//if(query.getVarietyNumber().shortValue()==0) query.setVarietyNumber(null);//默认前台不写条件为设为0，0不能生成查询条件
		return query;
	}
	
	/**
	 *  getImage 得到图片二进制内容
	 *  
	 *  @ResponseBody注解直接向客户端返回byte数组,框架自动转化为二进制流
	 *  
	 *  @param	String id:pk
	 *  
	 *  @return byte[]
	 */
	@RequestMapping(value="/getImage/{id}",method=RequestMethod.GET)
	@ResponseBody
	public byte[] getImage(@PathVariable("id") String id){
		MaizeExperiment entity = service.findOne(id);
		return entity.getPhoto();
	}
	
	@Override
	protected void initView(Map<String, Object> map) {
		MaizeExperiment entity = (MaizeExperiment)map.get("entity");
		map.put("varietiesJson", service.getVarieties(entity.getId()));
	}

	/**
	 *  初始化新增编辑页
	 */
	@Override
	protected void initAdd(Map<String, Object> map) {
		
	}
	
	/**
	 *  初始化更新编辑页
	 */
	@Override
	protected void initEdit(Map<String, Object> map) {
		MaizeExperiment entity = (MaizeExperiment)map.get("entity");
		//List<Function> funList = service.getFunList(entity.getId());
		map.put("varietiesJson", service.getVarieties(entity.getId()));
		service.getVarietyList(entity.getId(),"yieldPerMu");
		//map.put("funList", funList);
		//map.put("resultJson", service.getFunButJson(entity.getId(), funList));
	}
	
	/**
	 *  save	保存实体
	 *  
	 *  @param	MaizeExperiment	entity	接收页面提交玉米试验数据封装实体
	 *  @param	MultipartFile	file	接收页面提交文件二进制数据
	 *  @param	List<Variety> varieties	接收页面提交品种数据集合（由StringToVarietiesConverter转换）
	 *  
	 *  @return	String	返回页面路径
	 * @throws IOException 
	 */
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public String save(MaizeExperiment entity,
					   MultipartFile file,
					   @RequestParam("varietiesJson") List<Variety> varieties) throws Exception{
		SecurityUtils.getSubject().checkPermission(shortName + ":create");//检查当前用户是否有新增权限，没有抛出AuthorizationException
		if(file.getSize()>0) {
			entity.setPhoto(ImageUtil.getPhotoBytes(file, 512, 1027, 768));
		}
		try {
			service.save(entity,varieties);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/" + shortName + "/list";
	}

	/**
	 *  update	更新实体
	 *  
	 *  @param	MaizeExperiment	entity	接收页面提交玉米试验数据封装实体
	 *  @param	MultipartFile	file	接收页面提交文件二进制数据
	 *  @param	List<Variety> varieties	接收页面提交品种数据集合（由StringToVarietiesConverter转换）
	 *  
	 *  @return	String	返回页面路径
	 * @throws IOException 
	 */
	@RequestMapping(value="/update/{id}",method=RequestMethod.PUT)
	public String update(MaizeExperiment entity,
						 MultipartFile file,
						 @RequestParam("varietiesJson") List<Variety> varieties) throws IOException{
		SecurityUtils.getSubject().checkPermission(shortName + ":update");//检查当前用户是否有更新权限，没有抛出AuthorizationException
		if(file.getSize()>0) {
			entity.setPhoto(ImageUtil.getPhotoBytes(file, 512, 1027, 768));
		}
		try {
			//service.delateVarieties(entity.getId());
			service.update(entity,varieties);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/" + shortName + "/list";
	}
	
	 /**导出word
	 * @param String id
	 * @throws Exception
	 */
	@RequestMapping(value="/word/{id}",method=RequestMethod.GET)
	public ResponseEntity<byte[]> exportWord(@PathVariable("id") String id,
											 HttpSession session) throws Exception{
		byte[] body = null;
		ServletContext context = session.getServletContext();
		InputStream in = context.getResourceAsStream("WEB-INF/views/work/MaizeExperiment/玉米试验模板.docx");
		MaizeExperimentWordBuilder builder = new MaizeExperimentWordBuilder(in);
		String tmpdir = System.getProperty("java.io.tmpdir") ;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		String filename = sdf.format(date);
		builder.wordBuilder(service,id,tmpdir + filename + ".docx");
		File file = new File(tmpdir + filename + ".docx");//改成你本地文件所在目录
        FileInputStream fileInputStream = new FileInputStream(file);
		body = new byte[fileInputStream.available()];
		fileInputStream.read(body);
		fileInputStream.close();
		file.delete();
		
		HttpHeaders headers = new HttpHeaders();		
		headers.add("Content-Disposition", "attachment;filename=\"" + filename + ".docx\"");		
		HttpStatus statusCode = HttpStatus.OK;		
		ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body,headers,statusCode);
		
		return response;
	}
	
	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/excel/{id}",method=RequestMethod.GET)
	public ModelAndView exportExcel(@PathVariable("id") String id) throws Exception{
		
		Map<String,Object> map = new HashMap<String,Object>();
		List<String> titles = new ArrayList<String>();
		titles.add("品种名称");	
		titles.add("重复");	
		titles.add("穗长\r\n(cm)");	
		titles.add("穗粗\r\n(cm)");	
		titles.add("穗行数\r\n(行)");	
		titles.add("行粒数\r\n(粒)");	
		titles.add("粒色");	
		titles.add("粒型");	
		titles.add("穗型");	
		titles.add("穗轴色");	
		titles.add("穗腐病\r\n(%)");	
		titles.add("粒腐病\r\n(%)");	
		titles.add("秃尖度\r\n(cm)");	
		titles.add("千粒重\r\n(g)");	
		titles.add("鲜包重\r\n(kg)");	
		titles.add("干包重\r\n(kg)");	
		titles.add("干粒重\r\n(kg)");	
		titles.add("折籽率\r\n(%)");	
		titles.add("出籽率\r\n(%)");	
		titles.add("小区鲜重\r\n(kg)");	
		titles.add("小区产量\r\n(kg)");	
		titles.add("折合亩产\r\n(kg)");	
		map.put("titles", titles);
		List<Variety> list = service.getVarietyList(id);
		map.put("varList", list);
		
		MaizeBillExcelView erv = new MaizeBillExcelView();
		
		return new ModelAndView(erv,map);
	}
}
